using SG3L_RAG.Application.Interfaces;
using SG3L_RAG.Domain.Entities;
using SG3L_RAG.Domain.Repositories;

namespace SG3L_RAG.Application.Services
{
    public class LogService : ILogService
    {
        private readonly IRepository<Log> _logRepository;

        public LogService(IRepository<Log> logRepository)
        {
            _logRepository = logRepository;
        }

        public async Task<Log?> GetByIdAsync(Guid id)
        {
            return await _logRepository.GetByIdAsync(id);
        }

        public async Task<IEnumerable<Log>> GetAllAsync()
        {
            return await _logRepository.GetAllAsync();
        }

        public async Task<Log> CreateAsync(string type, string content, string? exceptionDetail = null)
        {
            var log = Log.Create(type, content, exceptionDetail);
            await _logRepository.AddAsync(log);
            return log;
        }

        public async Task UpdateAsync(Log log)
        {
            await _logRepository.UpdateAsync(log);
        }

        public async Task DeleteAsync(Guid id)
        {
            await _logRepository.DeleteAsync(id);
        }

        public async Task<IEnumerable<Log>> GetByTypeAsync(string type)
        {
            var logs = await _logRepository.GetAllAsync();
            return logs.Where(l => l.Type == type);
        }

        public async Task<IEnumerable<Log>> GetByDateRangeAsync(DateTime startDate, DateTime endDate)
        {
            var logs = await _logRepository.GetAllAsync();
            return logs.Where(l => l.CreatedAt >= startDate && l.CreatedAt <= endDate);
        }

        public async Task<IEnumerable<Log>> GetRecentLogsAsync(int count = 100)
        {
            var logs = await _logRepository.GetAllAsync();
            return logs.OrderByDescending(l => l.CreatedAt).Take(count);
        }

        public async Task<IEnumerable<Log>> GetErrorLogsAsync()
        {
            return await GetByTypeAsync("Error");
        }

        public async Task<IEnumerable<Log>> GetWarningLogsAsync()
        {
            return await GetByTypeAsync("Warning");
        }

        public async Task<IEnumerable<Log>> GetInfoLogsAsync()
        {
            return await GetByTypeAsync("Information");
        }

        public async Task LogInfoAsync(string content)
        {
            await CreateAsync("Information", content);
        }

        public async Task LogWarningAsync(string content)
        {
            await CreateAsync("Warning", content);
        }

        public async Task LogErrorAsync(string content, string? exceptionDetail = null)
        {
            await CreateAsync("Error", content, exceptionDetail);
        }

        public async Task CleanupOldLogsAsync(DateTime beforeDate)
        {
            var oldLogs = await GetByDateRangeAsync(DateTime.MinValue, beforeDate);
            var logIds = oldLogs.Select(l => l.Id);
            await _logRepository.DeleteRangeAsync(logIds);
        }
    }
}
